﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ETL.Business.Models;
using ETL.Common.Logging;
using ETL.DataAccess;
using ETL.Entity;

namespace ETL.Business.Handlers.ProjectHandlers
{
    public class UpdateProjectLeadEngineer
    {
        private readonly ProjectRepository _projectRepository;
        private readonly ProjectUserRepository _projectUserRepository;
        private readonly ProjectResourceInstanceRepository _projectResourceInstanceRepository;

        #region Constructor
        public UpdateProjectLeadEngineer()
        {
            _projectRepository = new ProjectRepository();
            _projectUserRepository = new ProjectUserRepository();
            _projectResourceInstanceRepository = new ProjectResourceInstanceRepository();
        }
        public UpdateProjectLeadEngineer(ProjectRepository projectRepository, ProjectUserRepository projectUserRepository, ProjectResourceInstanceRepository projectResourceInstanceRepository)
        {
            _projectRepository = projectRepository;
            _projectUserRepository = projectUserRepository;
            _projectResourceInstanceRepository = projectResourceInstanceRepository;
        }
        #endregion

        #region Methods
        public virtual int Execute(string projectId, string userId)
        {
            try
            {


            decimal _pId = 0;
            decimal.TryParse(projectId, out _pId);
            // Get current project
            var currentProject = _projectRepository.GetProjectByProjectId(_pId);

            // Check if current userId exist
            if (currentProject == null) return -1;

            // try to get from db
            IEnumerable<APP_USERS> allUsers = _projectUserRepository.GetAllAppUser();
            IEnumerable<RESOURCE_INSTANCES> allActiveUsers =
                _projectResourceInstanceRepository.GetAllResourceInstances();
            var projectUser = (from user in allUsers
                                   join activeUser in allActiveUsers
                                   on user.DSE_ID.ToUpper() equals activeUser.RESOURCE_NAME.ToUpper()
                                   where user.DSE_ID.ToUpper() == userId.ToUpper()
                                    select user).FirstOrDefault();

            if(projectUser != null)
            {
                currentProject.LEAD_ENGINEER_EMP_ID = userId;
                _projectRepository.UpdateProject(currentProject);
                return 1;
            }
                return 0;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return -1;
            }

        }
        #endregion

    }
}
